package com.ujiuye.demo;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

import java.util.Set;

public class JedisDemo {

    //单机版连接
    @Test
    public void test1() {
        Jedis jedis = new Jedis("192.168.21.129", 6379);
        //jedis.auth("登录密码");
        //向redis中存入字符串company
        jedis.set("company", "steam");
        System.out.println(jedis.get("company"));
        jedis.close();
    }


    //单机版连接池连接
    @Test
    public void testJedisPool() {
        JedisPoolConfig config = new JedisPoolConfig();
        config.setMaxIdle(10);
        config.setMinIdle(5);

        String host = "192.168.21.129";
        int port = 6379;
        int timeout = 30000;
        //string password=123456;

        JedisPool pool = new JedisPool(config, host, port, timeout);
        Jedis resource = pool.getResource();
        System.out.println(resource.get("username"));
        resource.close();
    }

    @Test
    public void testJedis() {
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext-redis.xml");
        JedisPool pool = (JedisPool) applicationContext.getBean("jedisPool");
        Jedis jedis = null;
        try {
            jedis = pool.getResource();
            jedis.set("testkey", "hello");
            String name = jedis.get("testkey");
            System.out.println(name);

            Long srem = jedis.srem("company2", "百度");
            System.out.println(srem);
            Set<String> company2 = jedis.smembers("company2");
            System.out.println(company2);

        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            if (jedis != null) {
                // 关闭连接
                jedis.close();
            }
        }
    }
}
